<?php
/**
 * 框架控制器基类
 * User: liuqingwei
 * Date: 2020/3/29
 * Time: 下午12:22
 */

namespace wei\core;

use library\render as render;

class Controller
{
    private $db;            //定义db链接
    private $view;
    protected static $route;
    
    protected  $request;
    
    /**
     * 初始化
     */
    public function __construct()
    {
        $this->view = new render\PhpRender();
        $this->request = new Request();
    }
    
    /**
     * 赋值给模版
     *
     * @param string        $key 变量键名
     * @param string|array  $val 值
     *
     * @return mixed
     */
    protected function assign($key,$val)
    {
        $this->view->assign($key,$val);
        return $this->view;
    }
    
    /**
     * Db调度
     *
     * @param array $conf 调度配置
     *
     * @return object
     */
    public function db(array $conf)
    {
        if (empty($conf))
        {
            $conf = $GLOBALS['_config']['db'];
        }
        
        $this->db = DB::getInstance($conf);
        return $this->db;
        
    }
    
    /**
     * 渲染
     *
     * @param string $file 视图名 路径
     *
     * @return mixed
     */
    public function display($file='')
    {
        if (func_num_args() == 0 || $file == NUll)
        {
            $control = self::$route->controller;
            $action  = self::$route->action;
            $view_file_path = _ROOT."app/".self::$route->group.'/module/view/';
            $view_file_path .= $control.DIRECTORY_SEPARATOR.$action.'.php';
        }
        else
        {
            $view_file_path = $file.'.php';
        }
        $this->view->display($view_file_path);
    }
    
    /**
     * 获取视图渲染的结果
     *
     * @param string $file 视图路径
     *
     * @return mixed
     */
    public function fetch($file='')
    {
        ob_start();
        ob_implicit_flush(0);
        $this->display($file);
        $contents = ob_get_clean();
        return $contents;
    }
}